package org.fioma.tree.suffixTree.memory;

import org.fioma.tree.bytes.LabelRefBytesIndex;
import org.fioma.tree.suffixTree.SuffixNode;

public abstract class SimpleSuffixNodeMemory<I extends InternalSuffixNodeMemory<I, F, N>, F extends LeafSuffixNodeMemory<I, F, N>, N extends SuffixNodeMemory<I, F, N>>
		implements SuffixNode<LabelRefBytesIndex, I, F, N>, SuffixNodeMemory<I, F, N> {

	protected long pos;
	protected SuffixTreeHandlerMemory<I, F, N> treeHandler;

	public SimpleSuffixNodeMemory(long pos, SuffixTreeHandlerMemory<I, F, N> treeHandler) {
		this.pos = pos;
		this.treeHandler = treeHandler;
	}

	public long getPos() {
		return pos;
	}

	public void setPos(long pos) {
		this.pos = pos;
	}

	public void setTreeHandler(SuffixTreeHandlerMemory<I, F, N> treeHandler) {
		this.treeHandler = treeHandler;
	}

	public SuffixTreeHandlerMemory<I, F, N> getTreeHandler() {
		return treeHandler;
	}

	@Override
	public I getParent() {
		long parentPos = treeHandler.getMemory().getParentAddress(getPos());
		return treeHandler.createInternalNode(parentPos);
	}

	@Override
	public void setParent(I parent) {
		treeHandler.getMemory().setParentAddress(getPos(), parent.getPos());

	}

	@Override
	public LabelRefBytesIndex getLabel() {
		int labelIndex = treeHandler.getMemory().getLabelIndex(getPos());
		int labelStart = treeHandler.getMemory().getLabelStart(getPos());
		int labelLength = treeHandler.getMemory().getLabelLength(getPos());
		return treeHandler.getLabelFactory().createLabel(labelIndex, labelStart, labelLength);
	}

	@Override
	public void setLabel(LabelRefBytesIndex label) {
		treeHandler.getMemory().setLabelIndex(getPos(), label.getIndex());
		treeHandler.getMemory().setLabelStart(getPos(), label.getStart());
		treeHandler.getMemory().setLabelLength(getPos(), label.getLength());
	}

	@Override
	public boolean isRoot() {
		return getParent() == null;
	}
}
